package com.utility.project.config;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${project.excludeUrl:}")
    private String excludeUrl;

    @Value("${data.auth.enabled:false}")
    private Boolean enabled;

    @Resource
    private DataAuthInterceptor dataAuthInterceptor;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        Set<String> patternSet = new HashSet();
        patternSet.add("/swagger-resources/**");
        patternSet.add("/webjars/**");
        patternSet.add("/v2/**");
        patternSet.add("/v3/**");
        patternSet.add("/doc.html");
        patternSet.add("/error");
        patternSet.add("/swagger-ui.html");
        patternSet.add("/swagger-ui/**");
        if (StrUtil.isNotBlank(this.excludeUrl)) {
            patternSet.addAll(Arrays.asList(this.excludeUrl.split(",", -1)));
        }

        List<String> patterns = patternSet.stream().collect(Collectors.toList());
        if(enabled){
            registry.addInterceptor(dataAuthInterceptor).addPathPatterns(new String[]{"/**"}).order(101).excludePathPatterns(patterns);;
        }
    }


}
